package cn.wolfcode.web.controller;


import cn.wolfcode.domain.Permission;
import cn.wolfcode.domain.Role;
import cn.wolfcode.queryobject.QueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRoleService;
import cn.wolfcode.util.RequiredPermission;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private IRoleService roleService;

    @Autowired
    private IPermissionService permissionService;

    //@RequiredPermission(name="部门列表",expression="role:list")
    @RequestMapping("/list")
    public String list(Model model, QueryObject qo){
        // 调用分页查询的方法
        PageInfo<Role> PageInfo = roleService.query(qo);
        // 往模型存数据
        model.addAttribute("PageInfo",PageInfo);
        // 找视图
        return "role/list";
    }

    // 处理删除请求
    @RequestMapping("/delete")
    @ResponseBody
    public String delete(Long id){

                if (id != null){
                roleService.delete(id);
            }
            return "redirect:/role/list.do";
    }

    // 去新增或去修改页面
    @RequestMapping("/input")
    public String input(Long id,Model model) {
        List<Permission> permissions = permissionService.listAll();
        model.addAttribute("permissions",permissions);

        if (id != null) { // 表示去修改
            model.addAttribute("role", roleService.selectOne(id));
        }
        return "role/input";
    }

    // 新增或修改
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Role role,Long[] ids) {
        if (role.getId() != null){ // 修改
            roleService.update(role,ids);

        }
        else{  // 新增
            roleService.insert(role,ids);
        }

        return "redirect:/role/list.do";// 让浏览器重新发送一次请求
    }
}
